package com.zliblike_platform.service.impl;

import com.zliblike_platform.dto.BookRequestDTO;
import com.zliblike_platform.dto.BookRequestUpdateDTO;
import com.zliblike_platform.entity.BookRequest;
import com.zliblike_platform.mapper.BookMapper;
import com.zliblike_platform.mapper.BookRequestMapper;
import com.zliblike_platform.mapper.UserMapper;
import com.zliblike_platform.service.BookRequestService;
import com.zliblike_platform.vo.BookRequestVO;
import com.zliblike_platform.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 书籍请求服务实现类
 */
@Service
public class BookRequestServiceImpl implements BookRequestService {

    @Autowired
    private BookRequestMapper bookRequestMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BookMapper bookMapper;
    
    @Override
    @Transactional
    public Long createRequest(Long userId, BookRequestDTO requestDTO) {
        // 检查ISBN是否已存在于请求中
        if (StringUtils.hasText(requestDTO.getIsbn()) && isbnExists(requestDTO.getIsbn())) {
            return null; // 返回null表示创建失败
        }
        
        // 创建请求实体
        BookRequest request = new BookRequest();
        request.setTitle(requestDTO.getTitle());
        request.setAuthor(requestDTO.getAuthor());
        request.setIsbn(requestDTO.getIsbn());
        request.setPublisher(requestDTO.getPublisher());
        request.setPubYear(requestDTO.getPubYear());
        request.setReason(requestDTO.getReason());
        request.setFormat(requestDTO.getFormat());
        request.setRequesterId(userId);
        request.setStatus("待处理"); // 初始状态为待处理
        
        Date now = new Date();
        request.setCreatedAt(now);
        request.setUpdatedAt(now);
        
        // 插入数据库
        bookRequestMapper.insert(request);
        
        return request.getRequestId();
    }
    
    @Override
    @Transactional
    public boolean updateRequestStatus(Long userId, BookRequestUpdateDTO updateDTO) {
        // 查询请求详情
        BookRequestVO existingRequest = bookRequestMapper.selectById(updateDTO.getRequestId());
        if (existingRequest == null) {
            return false;
        }
        
        // 检查状态是否合法
        String newStatus = updateDTO.getStatus();
        if (!isValidStatusTransition(existingRequest.getStatus(), newStatus)) {
            return false;
        }
        
        // 创建更新实体
        BookRequest request = new BookRequest();
        request.setRequestId(updateDTO.getRequestId());
        request.setStatus(newStatus);
        request.setUpdatedAt(new Date());
        
        // 根据状态设置不同字段
        if ("已拒绝".equals(newStatus)) {
            request.setRejectReason(updateDTO.getRejectReason());
            request.setFulfillerId(userId);
        } else if ("已接受".equals(newStatus)) {
            request.setFulfillerId(userId);
        } else if ("已完成".equals(newStatus)) {
            request.setFulfillerId(userId);
            request.setBookId(updateDTO.getBookId());
            
            // 检查书籍是否存在
            if (updateDTO.getBookId() != null && bookMapper.selectById(updateDTO.getBookId()) == null) {
                return false;
            }
        }
        
        // 更新数据库
        return bookRequestMapper.updateStatus(request) > 0;
    }
    
    @Override
    public PageResult<BookRequestVO> getAllRequests(String status, Integer page, Integer size) {
        Integer offset = (page - 1) * size;
        
        // 查询总记录数
        Integer total = bookRequestMapper.countAll(status);
        
        // 计算总页数
        Integer totalPages = (int) Math.ceil((double) total / size);
        
        // 查询记录
        List<BookRequestVO> records = bookRequestMapper.selectAllWithPagination(status, offset, size);
        
        return new PageResult<>(total, totalPages, page, records);
    }
    
    @Override
    public PageResult<BookRequestVO> getUserRequests(Long userId, String status, Integer page, Integer size) {
        Integer offset = (page - 1) * size;
        
        // 查询总记录数
        Integer total = bookRequestMapper.countByUserId(userId, status);
        
        // 计算总页数
        Integer totalPages = (int) Math.ceil((double) total / size);
        
        // 查询记录
        List<BookRequestVO> records = bookRequestMapper.selectByUserIdWithPagination(userId, status, offset, size);
        
        return new PageResult<>(total, totalPages, page, records);
    }
    
    @Override
    public BookRequestVO getRequestDetail(Long requestId, Long userId) {
        // 查询请求详情
        BookRequestVO request = bookRequestMapper.selectById(requestId);
        if (request == null) {
            return null;
        }
        
        // 判断当前用户是否可以编辑该请求
        boolean canEdit = canUserEditRequest(userId, request);
        request.setCanEdit(canEdit);
        
        return request;
    }
    
    @Override
    @Transactional
    public boolean deleteRequest(Long requestId, Long userId) {
        return bookRequestMapper.deleteById(requestId, userId) > 0;
    }
    
    @Override
    public boolean isbnExists(String isbn) {
        if (!StringUtils.hasText(isbn)) {
            return false;
        }
        return bookRequestMapper.existsByIsbn(isbn);
    }
    
    /**
     * 判断用户是否可以编辑请求
     * 
     * @param userId 用户ID
     * @param request 请求信息
     * @return 是否可以编辑
     */
    private boolean canUserEditRequest(Long userId, BookRequestVO request) {
        // 如果是请求者，且请求状态为"待处理"，可以编辑
        if (userId.equals(request.getRequesterId()) && "待处理".equals(request.getStatus())) {
            return true;
        }
        
        // 如果是管理员，可以编辑
        // TODO: 检查用户是否为管理员
        
        return false;
    }
    
    /**
     * 检查状态转换是否合法
     * 
     * @param currentStatus 当前状态
     * @param newStatus 新状态
     * @return 是否合法
     */
    private boolean isValidStatusTransition(String currentStatus, String newStatus) {
        // 根据业务规则定义合法的状态转换
        if ("待处理".equals(currentStatus)) {
            // 待处理 -> 已接受/已拒绝
            return "已接受".equals(newStatus) || "已拒绝".equals(newStatus);
        } else if ("已接受".equals(currentStatus)) {
            // 已接受 -> 已完成
            return "已完成".equals(newStatus);
        }
        
        return false;
    }
} 